const router=require('koa-router')();
const {User}=require('../models/index');
const {post:postProxy}=require('../proxy/index');
const config=require('../config/config');
const Page=require('../lib/page');
const checkPage=require('../middlewares/checkPage');

//Tags
router.get('/',async ctx=>{
    let [noRplies,top10]=await Promise.all([
       postProxy.getList({comments:{$size:0}},null,{limit:5}),
       User.find(null,{name:true,score:true},{skip:0,limit:5,sort:{score:-1}})
    ]);
    await ctx.render('tags',{
        title:'Tags',
        tags:config.post.tags,
        noReplies:noRplies.posts,
        top10,
        loginUser:ctx.session.loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error
    });
});

router.get('/:tag',checkPage(),async ctx=>{
    let {tag}=ctx.params;
    let [{total,page,posts},noReplies,top10]=await Promise.all([
        postProxy.getList({tags:{$in:[tag]}},null,{page:ctx.query.p}),
        postProxy.getList({comments:{$size:0}},null,{limit:5}),
        User.find(null,{name:true,score:true},{skip:0,limit:5,sort:{score:-1}})
    ]);
    await ctx.render('postList',{
        title:'Tag:'+tag,
        loginUser:ctx.session.loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error,
        posts:posts,
        noReplies:noReplies.posts,
        top10,
        page:Page(ctx.query,page,total)
    });
});

module.exports=router;